/**
 *  createc by jsq on 2017/11/10
 *  2018/12/20优化代码
 */
import React from 'react';
import { Button, Form, Select,Input, Col, Row, Switch, message, Icon} from 'antd';
import { connect } from 'react-redux';
import {messages} from "share/common";
import httpFetch from 'share/httpFetch';
import config from 'config';
import menuRoute from 'routes/menuRoute';
import 'styles/setting/company-group/new-company-group.scss';
import companyGroupService from 'containers/setting/company-group/company-group.service';
import LanguageInput from 'components/template/language-input/language-input';

const FormItem = Form.Item;
const Option = Select.Option;

class NewCompanyGroup extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      statusCode: messages('common.enabled'),  /*启用*/
      setOfBooks: [],
      companyGroupName: [], //公司组名称国际化
      name: ''
    };
  }

  componentWillMount(){
    httpFetch.get(`${config.baseUrl}/api/setOfBooks/by/tenant?roleType=TENANT`).then((response)=>{
      let setOfBooks = [];
      response.data.map((item)=>{
        let option = {
          value: item.setOfBooksCode +" - "+item.setOfBooksName,
          id: item.id
        };
        setOfBooks.addIfNotExist(option)
      });
      this.setState({
        setOfBooks:setOfBooks
      });
    });
  }

  componentDidMount(){
    let id = this.props.params.companyGroupId;
    if(id !== 'NEW'){
      companyGroupService.getCompanyGroupById(id).then(res => {
        this.props.form.setFieldsValue({
          companyGroupCode: res.data.companyGroupCode,
          setOfBooksId: res.data.setOfBooksId,
          enabled: res.data.enabled,
          companyGroupName: res.data.companyGroupName
        });
        this.setState({
          companyGroupName: res.data.i18n.companyGroupName,
          name: res.data.companyGroupName,
          statusCode: res.data.enabled ? messages('common.enabled') : messages('common.disabled')
        })
      });
    }
  }


  //新建公司组
  handleSave = (e) =>{
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({ loading: true });
        values.i18n = {};
        values.i18n.companyGroupName = this.state.companyGroupName;
        let id = this.props.params.companyGroupId;
        if(id !== 'NEW'){
          values.id = id;
          companyGroupService.updateCompanyGroup(values).then((response)=>{
            if(response) {
              message.success(messages('setting.key256'/*保存成功！*/));
              window.history.go(-1);
            }
          }).catch((e)=>{
            if(e.response){
              message.error(`${messages('common.save.filed')}, ${e.response.data.message}`);
              this.setState({loading: false});
            }
          })
        } else {
          companyGroupService.addCompanyGroup(values).then((response)=>{
            if(response) {
              message.success(messages('setting.key256'/*保存成功！*/));
              let url = menuRoute.getMenuItemByAttr('company-group', 'key').children.companyGroupDetail.url;
              url = url.replace(':id',response.data.id);
              this.context.router.push(url);
              this.setState({loading:false})
            }
          }).catch((e)=>{
            if(e.response){
              message.error(`${messages('common.save.filed')}, ${e.response.data.message}`);
              this.setState({loading: false});
            }
          })
        }
      }
    });
  };

  //点击取消，返回预算组织详情
  handleCancel = (e) =>{
    e.preventDefault();
    window.history.go(-1);
  };

  handleChange = ()=>{
    if(this.state.loading){
      this.setState({
        loading: false
      })
    }
  };

  //修改公司组名称
  handleNameChange = (value, i18n) => {
    this.setState({ name: value, companyGroupName: i18n })
  };

  render(){
    const { statusCode, loading, setOfBooks, name, companyGroupName } = this.state;
    const {params,form} = this.props;
    const getFieldDecorator = form.getFieldDecorator;
    const isEdit = params.companyGroupId !== 'NEW';
    return(
      <div className="new-company-group">
        <Form onSubmit={this.handleSave} onChange={this.handleChange}>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('setting.key244'/*公司组代码*/)}
                colon={true}>
                {getFieldDecorator('companyGroupCode', {
                  rules:[
                    { required:true, message: messages('common.please.enter') },
                    // 公司组代码前端不做校验，使用后端提示
                  ]
                })(
                  <Input placeholder={messages('common.please.enter')} disabled={isEdit}/>)
                }
              </FormItem>
              <div className="company-group-tips">
                {messages('setting.key257'/*注：公司组代码保存后将不可修改*/)}
              </div>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('setting.key245'/*公司组名称*/)}
                colon={true}>
                {getFieldDecorator('companyGroupName', {
                  rules:[
                    {required:true,message:messages('common.please.enter')
                    },
                    {
                      validator: (item,value,callback)=>{
                        //tasK 11880
                        // let str = /^[\u4E00-\u9FA5\w\d]*$/u;
                        // if(value && (!str.test(value)||value.length >100)){
                        //   callback(messages('setting.key258'/*不超过100个字符，只能有中文，数字，字母，下划线。*/))
                        // }
                        callback();
                      }
                    }
                  ]
                })(
                  <LanguageInput nameChange={this.handleNameChange}
                                 name={name}
                                 i18nName={companyGroupName}
                                 isEdit={isEdit}/>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('setting.key246'/*账套*/)}
                colon={true}>
                {getFieldDecorator('setOfBooksId', {
                  rules:[
                    {required:true,message:messages('common.please.select')},
                  ]
                })(
                  <Select placeholder={messages('common.please.select')}
                          disabled={isEdit}>
                    {
                      setOfBooks.map((item)=><Option key={item.id}>{item.value}</Option>)
                    }
                  </Select>)
                }
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('common.status',{status:statusCode})} /* {/!*状态*!/}*/
                colon={false}>
                {getFieldDecorator("enabled", {
                  initialValue: true,
                  valuePropName: 'checked',
                  rules:[
                    {
                      validator: (item,value,callback)=>{
                        this.setState({
                          statusCode: value ? messages('common.enabled') /*启用*/
                            : messages('common.disabled') /*禁用*/
                        });
                        callback();
                      }
                    }
                  ],
                })
                (<Switch checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="cross"/>}/>)
                }
              </FormItem>
            </Col>
          </Row>
          <Button type="primary" loading={loading} htmlType="submit">{messages('common.save') /*保存*/}</Button>
          <Button onClick={this.handleCancel} style={{ marginLeft: 8 }}> {messages('common.cancel') /*取消*/}</Button>
        </Form>
      </div>
    )
  }
}

NewCompanyGroup.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}



const WrappedNewCompanyGroup = Form.create()(NewCompanyGroup);

export default connect(mapStateToProps)(WrappedNewCompanyGroup);
